<template>
  <div class="row">
    <div class="col-md-12">
      <FrontSideTable
        v-show="currentPage === 0"
        ref="taskTable"
        :dataUrl="'/task/'+taskTypeName+'/getList'"
        tableTitle="任务单列表"
        :columns="columns"
        searchHint="输入关键字进行查找，多个关键字用空格隔开"
        :searchProps="searchProps"
        :addable="canAdd"
        @onCreated="handleCreated"
        @beforeAdd="handleTaskAdd"
        customButton
        customFormDialog>
        <!--任务单进度列-->
        <template slot="afterColumns">
          <el-table-column label="任务单进度" align="center" width="180">
            <template slot-scope="scope">
              <ProgressBar :total="scope.row.total" :progress="scope.row.progress"></ProgressBar>
            </template>
          </el-table-column>

          <el-table-column label="完成桥数" align="center" width="100">
            <template slot-scope="scope">
              <ProgressIndicator :total="scope.row.total" :progress="scope.row.progress"></ProgressIndicator>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="170">
            <template slot-scope="scope">
              <el-button v-if="canEdit && scope.row.manager === $store.state.User.currentUser.id" size="mini" @click="handleTaskEdit(scope.row)">编辑</el-button>
              <el-button v-if="canManage" size="mini" type="success" @click="handleInspection(scope.row)">桥梁</el-button>
              <el-button v-if="scope.row.manager === $store.state.User.currentUser.id && scope.row.total === scope.row.progress" size="mini" type="warning" @click="handleTaskFinish(scope.row)">结束</el-button>
              <el-button v-if="canDelete && scope.row.manager === $store.state.User.currentUser.id && scope.row.total > scope.row.progress" size="mini" type="danger" @click="handleTaskDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </template>

        <!--添加检测人员-->
        <template slot="dialog">
          <!--  新增或编辑对话框  -->
          <el-dialog :title="updateDialogTitle" size="large" v-model="isUpdateDialogVisible" :close-on-click-modal="false">
            <el-form ref="taskForm" :model="form" label-width="150px" v-loading="loadingForm">
              <div class="row">
                <!--  左侧树形菜单  -->
                <div class="col-md-3">
                  <!--  新增按钮  -->
                  <a href="javascript:void(0)" class="btn btn-primary btn-block margin-bottom" @click="isInspectorDialogVisible = true">检测人员管理</a>
                  <!--  树形菜单  -->
                  <div class="box box-primary">
                    <div class="box-header with-border">
                      <h3 class="box-title">检测人员列表</h3>
                    </div>
                    <el-tree
                      class="tree-view"
                      node-key="id"
                      :treeProps="{label:'name'}"
                      :data="inspectors"
                      :render-content="renderContent">
                    </el-tree>
                  </div>
                </div>

                <!--检测桥梁-->
                <div class="col-md-9">
                  <PaginationTable
                    tableTitle="检测桥梁列表"
                    :dataList="form.bridgeList"
                    :columns="bridgeColumns"
                    searchHint="输入关键字进行搜索，多个关键字用空格隔开"
                    :searchProps="selectedBridgeSearchProps"
                    @onAdd="handleBridgeAdd"
                    canAdd>
                    <!--操作列-->
                    <el-table-column label="操作" align="center" width="100px">
                      <template slot-scope="scope">
                        <el-button size="small" type="danger" @click="handleBridgeDelete(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </PaginationTable>
                </div>
              </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="isUpdateDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateTask" :loading="isTaskUpdating">确 定</el-button>
            </div>
          </el-dialog>

          <!--检测人员对话框-->
          <el-dialog title="检测人员选择" size="tiny" v-model="isInspectorDialogVisible" :close-on-click-modal="false">
            <el-select v-model="form.userIds" style="width: 100%;" placeholder="(多选)选择检测人员" multiple filterable>
              <el-option-group v-for="group of treeUserList" :key="group.name" :label="group.name">
                <el-option v-for="item of group.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-option-group>
            </el-select>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="isInspectorDialogVisible = false">确 定</el-button>
            </div>
          </el-dialog>

          <!--添加检测桥梁-->
          <el-dialog title="检测桥梁选择" size="small" v-model="isBridgeDialogVisible" :close-on-click-modal="false">
            <Table
              ref="bridgeTable"
              v-loading="loadingBridgeTable"
              title="请选择检测桥梁"
              :pageData="bridgePageData"
              searchHint="输入关键字搜索，多个关键字用空格隔开"
              @sizeChange="handleBridgeTableSizeChange"
              @pageTurning="handleBridgeTablePageTurning"
              @sortChange="handleBridgeTableSortChange"
              @filterChange="handleBridgeTableFilterChange"
              @search="handleBridgeTableSearch"
              @select="handleBridgeSelect"
              @selectAll="handleBridgeSelectAll">
              <!--索引列-->
              <el-table-column type="selection" width="50"></el-table-column>
              <!--表格主体内容-->
              <el-table-column v-for="col of bridgeColumns"
                               align="center"
                               :key="col.prop"
                               :prop="col.prop"
                               :label="col.label"
                               :width="col.width"
                               :sortable="col.sortable">
              </el-table-column>
            </Table>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="isBridgeDialogVisible = false">确 定</el-button>
            </div>
          </el-dialog>
        </template>
      </FrontSideTable>

      <!--第二层：桥梁界面-->
      <TaskBridge
        v-if="currentPage === 1"
        :currentTask="currentTask"
        :rootUrl="'/task/'+taskTypeName"
        :dataParam="{taskId:currentTask.id}"
        :tableTitle="!!currentTask.name?currentTask.name:''"
        @onBack="handleBack">
      </TaskBridge>
    </div>
  </div>
</template>

<script>
  import TaskBridge from "../template/TaskBridge.vue"
  import FrontSideTable from "../template/FrontSideTable.vue"
  import Table from "../../components/content/bridge/Table.vue"
  import PaginationTable from "../template/PaginationTable.vue"
  import {doDelete, doGet, doPost} from "../../assets/js/utils/RequestUtils"
  import {clearFields} from "../../assets/js/utils/ObjectUtils"
  import {childrenArrayOf} from "../../assets/js/utils/TreeUtils"
  import ProgressBar from "../template/ProgressBar.vue"
  import ProgressIndicator from "../template/ProgressIndicator.vue"
  import {hasAuthorizedFunction, getAuthorizedFunction} from "../../assets/js/global"
  import {ADD, ADD_TASK, DELETE, EDIT, MANAGE} from "../../assets/js/enum/FunctionType";
  import {SUCCESS} from "../../assets/js/enum/RequestResult";
  import {FREQUENT_INSPECTION, REGULAR_INSPECTION, SPECIAL_INSPECTION} from "../../assets/js/enum/TaskType";

  //桥梁列表获取地址
  const BRIDGE_URL = "/bridge/bridge/getNonExecutionBridgePageData";

  export default {
    name:"TaskManagement",
    props:{
      taskType: {
        type:Number,
        required:true
      }
    },
    data() {
      return {
        //当前页面，共三层：任务单、桥梁、病害
        currentPage:0,
        currentTask:{},
        taskList:[],
        //主界面
        columns:[
          {prop:"name", label:"任务单名称"},
          {prop:"managerName", label:"负责人", width:"150"},
          {prop:"startDate", label:"下发时间", width:"150"}
        ],
        searchProps:["name", "manageName", "startDate", "jointBridgeNames"],
        //新增或编辑表单
        loadingForm:false,
        isTaskUpdating:false,
        isUpdateDialogVisible:false,
        updateType:ADD,
        form:{
          userIds:[],
          bridgeList:[]
        },
        userList:[],
        selectedBridgeSearchProps:["name", "roadNo", "fullAddressName", "unitsName"],
        //桥梁选择对话框
        bridgePageData:{
          data:[],
          pageSize:10,
          total:0,
          currentPage:1
        },
        bridgeSearchValues:[],
        bridgeSortProp:"",
        bridgeOrder:"",
        bridgeFilter:{prop:"", values:[]},
        loadingBridgeTable:false,
        isBridgeDialogVisible:false,
        bridgeColumns:[
          {prop:"name", label:"桥名"},
          {prop:"roadNo", label:"路线号", sortable:"custom"},
          {prop:"fullAddressName", label:"所在地"},
          {prop:"unitsName", label:"管养单位"}
        ],
        //检测人员选择框
        isInspectorDialogVisible:false
      }
    },
    computed: {
      treeUserList() {
        let result = [];
        let unitsSet = new Set();
        this.userList.forEach(user=>unitsSet.add(user.unitsName));
        [...unitsSet].forEach(units=>result.push({children:childrenArrayOf(units, this.userList), name:units}));
        return result;
      },
      updateDialogTitle() {
        switch(this.updateType) {
          case ADD:
            return "新增";
          case EDIT:
            return "编辑";
          default:
            return "新增";
        }
      },
      taskTypeName() {
        switch(this.taskType) {
          case FREQUENT_INSPECTION:
            return "frequent";
          case REGULAR_INSPECTION:
            return "regular";
          case SPECIAL_INSPECTION:
            return "special";
        }
      },
      inspectors() {
        return this.userList.filter(user=>this.form.userIds.includes(user.id));
      },
      canAdd() {
        return hasAuthorizedFunction(this, ADD_TASK);
      },
      canEdit() {
        return hasAuthorizedFunction(this, EDIT);
      },
      canManage() {
        return hasAuthorizedFunction(this, MANAGE);
      },
      canDelete() {
        return hasAuthorizedFunction(this, DELETE);
      }
    },
    methods:{
      handleCreated(data) {
        this.taskList = data;
      },
      handleTaskAdd() {
        //执行初始化动作
        clearFields(this.form);
        //设置检查类型
        this.form.type = this.taskType;
        //打开对话框
        this.updateType = ADD;
        this.isUpdateDialogVisible = true;
      },
      handleInspection(task) {
        this.currentTask = task;
        this.currentPage = 1;
      },
      handleTaskEdit(task) {
        this.loadingForm = true;
        this.form = {...task};
        let hasDone = 0;
        //加载选中的用户
        doGet("/task/"+this.taskTypeName+"/getSelectedUserIds", {data:{taskId:task.id}, component:this})
          .then(response=>this.form.userIds = response)
          .finally(()=>{
            if(hasDone === 1) this.loadingForm = false;
            else hasDone++;
          });
        //加载选中的桥梁
        doGet("/task/"+this.taskTypeName+"/getSelectedBridges", {data:{taskId:task.id}, component:this})
          .then(response=>this.form.bridgeList = response)
          .finally(()=>{
            if(hasDone === 1) this.loadingForm = false;
            else hasDone++;
          });
        //打开对话框
        this.updateType = EDIT;
        this.isUpdateDialogVisible = true;
      },
      handleTaskFinish(rowData) {
        if(rowData.progress === rowData.total) {
          this.$confirm("任务单结束后，任务单信息及病害数据将移入历史数据库, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            doDelete("/task/" + this.taskTypeName + "/finish", {
              data: rowData,
              menuFunctionId: getAuthorizedFunction(this, DELETE),
              component: this
            })
              .then(response => {
                this.$message({message: response.message, type: response.status.toLowerCase()});
                this.$refs["taskTable"].fetchData();
              });
          });
        }else {
          this.$alert("尚有桥梁未通过审核，请在通过审核后再结束任务单", "提示");
        }
      },
      handleTaskDelete(rowData) {
        this.$confirm("此操作将永久删除该任务单及该任务单下所记录的病害, 是否继续?", "提示", {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }).then(()=>{
          doDelete("/task/"+this.taskTypeName+"/delete", {
            data:rowData,
            menuFunctionId:getAuthorizedFunction(this, DELETE),
            component:this
          })
            .then(response => {
              this.$message({message:response.message, type:response.status.toLowerCase()});
              this.$refs["taskTable"].fetchData();
            });
        });
      },
      handleBridgeTableSizeChange(pageSize) {
        this.bridgePageData.pageSize = pageSize;
        this.fetchBridgeTableData();
      },
      handleBridgeTablePageTurning(index) {
        this.bridgePageData.currentPage = index;
        this.fetchBridgeTableData();
      },
      handleBridgeTableSortChange({column, prop, order}) {
        this.bridgeSortProp = prop;
        this.order = order;
        this.fetchBridgeTableData();
      },
      handleBridgeTableFilterChange(filter) {
        this.filter = filter;
        this.fetchBridgeTableData();
      },
      handleBridgeTableSearch(value) {
        this.bridgeSearchValues = value.split(" ");
        this.fetchBridgeTableData();
      },
      handleBridgeSelect(selection, row) {
        let index = this.form.bridgeList.findIndex(item=>item.id === row.id);
        if(index >= 0) this.form.bridgeList.splice(index, 1);
        else this.form.bridgeList.push(row);
      },
      handleBridgeSelectAll(selection) {
        if(selection.length === 0) {
          this.form.bridgeList = this.form.bridgeList.filter(item=>!this.bridgePageData.data.find(i=>i.id === item.id));
        } else {
          selection.forEach(item=>{
            if(!this.form.bridgeList.find(i=>i.id === item.id)) {
              this.form.bridgeList.push(item);
            }
          })
        }
      },
      handleBridgeAdd() {
        this.fetchBridgeTableData();
        this.isBridgeDialogVisible = true;
      },
      handleBridgeDelete(data) {
        this.form.bridgeList.splice(this.form.bridgeList.findIndex(item=>item.id === data.id), 1);
      },
      handleInspectorDelete(data) {
        this.form.userIds.splice(this.form.userIds.findIndex(item=>item === data.id), 1);
      },
      handleBack() {
        this.currentPage = 0;
        this.$Loading.start();
        doGet("/task/"+this.taskTypeName+"/getTaskById", {
          data:{id:this.currentTask.id},
          componentId:this
        }).then(response=>{
          this.taskList.filter(t=>t.id === this.currentTask.id).forEach(t=>{
            t.progress = response.progress;
            t.total = response.total;
          });
        })
          .finally(()=>{
            this.$Loading.finish();
            this.currentTask = {};
          });
      },
      renderContent(h, {node, data, store}) {
        return h('span', {style:"display:inline-block;width:100%;overflow:hidden;"},[
          h('span', {}, [data.name]),
          h('el-button', {style:"float:right;margin:8px 36px", props:{type:"danger", icon:"delete", size:"mini"}, on:{click:()=>this.handleInspectorDelete(data)}}, [])
        ]);
      },

      fetchBridgeTableData() {
        this.loadingBridgeTable = true;
        doGet(BRIDGE_URL, {
          data: {
            taskType: this.taskType,
            pageSize: this.bridgePageData.pageSize,
            currentPage: this.bridgePageData.currentPage,
            searchArray: this.bridgeSearchValues,
            sortProp: this.bridgeSortProp,
            order: this.bridgeOrder
          },
          component: this
        })
          .then(response => this.bridgePageData = response)
          .finally(() => {
            this.checkDefaultRows();
            this.loadingBridgeTable = false
          })
      },
      updateTask() {
        let updateUrl = "/task/"+this.taskTypeName+"/add";
        if(this.updateType === EDIT) updateUrl = "/task/"+this.taskTypeName+"/edit";
        this.$refs["taskForm"].validate(valid=>{
          if(valid) {
            this.isTaskUpdating = true;
            this.$emit("onUpdate");
            doPost(updateUrl, {
              data:this.form,
              menuFunctionId:getAuthorizedFunction(this, this.updateType),
              component:this
            })
              .then(response => {
                //服务端返回成功，则进行后续操作
                if(response.status === SUCCESS) {
                  this.$message({message: response.message, type: response.status.toLowerCase()});
                  this.isUpdateDialogVisible = false;
                  this.$refs["taskTable"].fetchData();
                } else {
                  this.$alert(response.message, "提示", {confirmButtonText:"确定"})
                }
              })
              .finally(()=>this.isTaskUpdating = false)
          }
        });
      },

      /*  勾选默认选中的行 */
      checkDefaultRows() {
        if(this.$refs["bridgeTable"]) {
          this.bridgePageData.data.forEach(item=>{
            if(this.form.bridgeList.find(bridge=>bridge.id === item.id)) {
              this.$refs["bridgeTable"].toggleRowSelection(item, true);
            } else {
              this.$refs["bridgeTable"].toggleRowSelection(item, false);
            }
          })
        }
      }
    },
    created() {
      //加载所有的用户
      doGet("/task/"+this.taskTypeName+"/getUserListByCurrentUser", {component:this})
        .then(response=>this.userList = response);
    },
    components:{TaskBridge, FrontSideTable, Table, PaginationTable, ProgressBar, ProgressIndicator}
  }
</script>

<style scoped>
  .tree-view {
    border: 0;
  }
</style>



// WEBPACK FOOTER //
// TaskManagement.vue?d72c3402
